package com.xsdl.giteespringboottest.service.impl;

import cn.hutool.core.lang.UUID;
import cn.hutool.core.map.MapUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.xsdl.giteespringbootautoconfigure.GiteeAutoConfiguration;
import com.xsdl.giteespringboottest.dao.UserAppDao;
import com.xsdl.giteespringboottest.dao.UserDao;
import com.xsdl.giteespringboottest.dto.UserDTO;
import com.xsdl.giteespringboottest.pojo.User;
import com.xsdl.giteespringboottest.pojo.UserApp;
import com.xsdl.giteespringboottest.service.GiteeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Map;

@Service("giteeService")
@Slf4j
public class GiteeServiceImpl implements GiteeService {

    @Autowired
    private GiteeAutoConfiguration giteeClient;
    @Autowired
    private UserAppDao userAppDao;
    @Autowired
    private UserDao userDao;

    @Override
    public UserDTO login(String code) {
        UserDTO result = new UserDTO();

        // 通过授权码去拿 accessToken todo 存储 accessToken
        Map<String, Object> giteeAuthInfo = giteeClient.getGiteeAccessToken(code);
        String accessToken = MapUtil.getStr(giteeAuthInfo, "access_token");
        if (StringUtils.isEmpty(accessToken)) {
            log.error("获取token失败");
            throw new RuntimeException("获取token失败");
        }

        // 通过 accessToken 去取用户信息
        Map<String, Object> giteeUserInfo = giteeClient.getGiteeUserInfo(accessToken);
        String giteeOpneId = MapUtil.getStr(giteeUserInfo, "id");

        // 取 giteeUserInfo 中的唯一标识
        if (StringUtils.isEmpty(giteeOpneId)) {
            log.error("获取gitee中的openId失败");
            throw new RuntimeException("gitee标识为空");
        }

        // 在数据库中找是否已经注册,否则新建用户并绑定
        List<UserApp> giteeUser = userAppDao.findAllByAppAndAppOpenId("gitee", giteeOpneId);
        if (giteeUser.isEmpty()) {

            String giteeName = MapUtil.getStr(giteeUserInfo, "name");
            String giteeEmail = MapUtil.getStr(giteeUserInfo, "email");

            // 在数据库中新建一个用户,与其关联
            User user = new User();
            user.setUuid(UUID.randomUUID().toString())
                    .setName(giteeName)
                    .setEmail(giteeEmail);

            UserApp userApp = new UserApp();
            userApp.setUuid(UUID.randomUUID().toString())
                    .setApp("gitee")
                    .setToken(accessToken)
                    .setUserId(user.getUuid())
                    .setAppOpenId(giteeOpneId);

            getThis().doSave(user, userApp);
            BeanUtils.copyProperties(user, result);
        } else {
            UserApp userApp = giteeUser.get(0);
            User user = userDao.findById(userApp.getUserId()).orElse(null);
            if (user == null) {
                log.error("数据非法,AppUser中有信息,User中无信息");
                throw new RuntimeException("内部逻辑错误");
            }
            BeanUtils.copyProperties(user, result);
        }

        return result;
    }

    @Transactional
    public void doSave(User user, UserApp userApp) {
        userDao.save(user);
        userAppDao.save(userApp);
    }

    public GiteeServiceImpl getThis() {
        ApplicationContext context = SpringUtil.getApplicationContext();
        return context.getBean(GiteeServiceImpl.class);
    }

}
